package com.thyrsus.project.controller.user;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.thyrsus.project.form.user.UserForm;
import com.thyrsus.project.helper.Constants;
import com.thyrsus.project.helper.LocaleHelper;
import com.thyrsus.project.helper.SessionHelper;
import com.thyrsus.project.helper.URLHelper;
import com.thyrsus.project.object.UserContext;
import com.thyrsus.project.service.user.UserService;

import org.apache.log4j.Logger;

@Controller
@SessionAttributes
public class ConnexionUserController {
	
	static Logger LOGGER = Logger.getLogger(ConnexionUserController.class);
	
	@Autowired
	UserService userService;
	
	@RequestMapping(value = "/user/login", method = RequestMethod.POST)
    public ModelAndView doLogin(@ModelAttribute("userForm")
                            UserForm userForm, BindingResult result, HttpServletRequest request,HttpServletResponse response) {
		
		LOGGER.debug(userForm.getMail()+" is login' in with the password : "+userForm.getPassword());
		UserContext userContext = userService.login(userForm.getMail(),
				userForm.getPassword());
		if (userContext!=null) {
			LOGGER.debug("The id of the user is : "+userContext.getId());
			SessionHelper.setAttribute(request, Constants.USER_CONTEXT, userContext);
			SessionHelper.removeAttribute(request, Constants.ERROR_LOGIN);
			LocaleHelper.setLocale(userContext.getLocale(), request, response);
		} else {
			LOGGER.debug("Error login...");
			SessionHelper.setAttribute(request,Constants.ERROR_LOGIN, "error");
			userForm.setPassword("");
		}
		
		return new ModelAndView(URLHelper.getURL("/user/login-ajax_result",request));
	}
	
	
	
	@RequestMapping(value = "/user/logout")
    public String doLogout(HttpServletRequest request,HttpServletResponse response) {
		LOGGER.debug("logout function called");
		SessionHelper.removeAttribute(request, Constants.USER_CONTEXT);
		return "redirect:/home";
	}
}
